import {
  CheckCircleOutlined,
  PlusOutlined,
  SearchOutlined,
  UploadOutlined,
} from '@ant-design/icons';
import {
  Button,
  message,
  Drawer,
  FormInstance,
  Popconfirm,
  Image,
  Modal,
  Upload,
  Tag,
  Divider, Switch,
} from 'antd';
import React, {useState, useRef, useEffect} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import type {ProColumns, ActionType} from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  ModalForm,
  ProFormText,
  ProFormRadio,
  ProFormSelect,
  ProFormDateRangePicker,
  ProFormDependency,
  ProFormDigit,
  DrawerForm,
  ProForm,
  ProFormCascader,
  ProFormDatePicker,
} from '@ant-design/pro-form';
import ProDescriptions, {ProDescriptionsItemProps} from '@ant-design/pro-descriptions';
import {
  removeData,
  dataList,
  addData,
  updateData,
  loadData,
  loadSelectTag,
  questionList,
  coursewareList,
  coursewareListSave,
  updateCourse,
  employeeListSave,
  employeeList,
  publishData,
  unPublishData, saveAuto, checkAuto, genPlan,
} from './service';
import type {PlanBody, PlanListItem, PlanListPagination} from './data';

import {CoursewareItem, QuestionItem} from './data';
import CoursewareList from '@/pages/Train/Courseware/list';
import {CoursewareListItem} from '@/pages/Train/Courseware/data';
import {download} from '@/pages/Train/Courseware/service';
import {EmployeeListItem} from '@/pages/Employee/List/data';
import moment, {Moment} from 'moment';
import 'moment/locale/zh-cn';
import {loadOrgSelect, sensitiveTest} from '@/pages/Enterprise/Org/service';
import PlanEmployeeSelect from '@/pages/Train/Plan/employee';
import CheckModule from '@/components/CheckModule';
import {checkFirst, doFirst} from "@/pages/Defense/Database/Risk/service";

/**
 * 添加节点
 *
 * @param fields
 * @param mode
 */

const handleAdd = async (fields: PlanBody, mode: boolean) => {
  const hide = message.loading(mode ? '正在保存' : '正在添加');

  try {
    mode ? await updateData({...fields}) : await addData({...fields});
    hide();
    message.success(mode ? '保存成功' : '添加成功');
    return true;
  } catch (error) {
    // hide();
    // message.error(mode ? '保存失败请重试' : '添加失败请重试');
    return false;
  }
};
const handleSaveCourse = async (fields: PlanBody) => {
  const hide = message.loading('正在保存');

  try {
    await updateCourse({...fields});
    hide();
    message.success('保存成功');
    return true;
  } catch (error) {
    hide();
    message.error('保存失败请重试');
    return false;
  }
};
/**
 * 删除节点
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: PlanListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await removeData(selectedRows.map((row) => row.planId));
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};
const handlePublish = async (selectedRows: PlanListItem) => {
  const hide = message.loading('正在发布');
  if (!selectedRows) return true;
  try {
    await publishData(selectedRows.planId);
    hide();
    message.success('发布成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('发布失败，请重试');
    return false;
  }
};
const handleUnPublish = async (selectedRows: PlanListItem) => {
  const hide = message.loading('正在取消发布');
  if (!selectedRows) return true;
  try {
    await unPublishData(selectedRows.planId);
    hide();
    message.success('取消发布成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('取消发布失败，请重试');
    return false;
  }
};

const requestTag = async () => {
  return loadSelectTag().then(({data}) => {
    return data;
  });
};
const PlanPage: React.FC = (props, context) => {
  const [category, setCategory] = useState<number>(0);

  useEffect(() => {
    if (location.pathname == '/train/plan/post') {
      setCategory(1);
    }
  }, []);

  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [coursewareModalVisible, handleCoursewareModalVisible] = useState<boolean>(false);
  const [employeeModalVisible, handleEmployeeModalVisible] = useState<boolean>(false);
  const [selectCoursewareModalVisible, handleSelectCoursewareModalVisible] =
    useState<boolean>(false);
  const [selectEmployeeModalVisible, handleSelectEmployeeModalVisible] = useState<boolean>(false);
  const [coursewareType, setCoursewareType] = useState<number>(1);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [orgSelectAll, setOrgSelectAll] = useState<[][number]>([][0]);
  const actionRef = useRef<ActionType>();
  const actionQuestionRef = useRef<ActionType>();
  const actionCoursewareRef = useRef<ActionType>();
  const actionEmployeeRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const formCoursewareRef = useRef<FormInstance>();
  const [currentRow, setCurrentRow] = useState<PlanListItem>();
  const columns: ProColumns<PlanListItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      align: 'center',
      valueType: 'indexBorder',
      render: (dom, entity, index) => {
        return (
          <span>
            {index +
              1 +
              ((actionRef?.current?.pageInfo?.current || 1) - 1) *
              (actionRef?.current?.pageInfo?.pageSize || 5)}
          </span>
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInDescriptions: true,
      render: (_, record) => {
        if (record.publish == 0 && record.isOwner) {
          return [
            <a
              key="view"
              onClick={() => {
                formRef.current?.resetFields();
                setCurrentRow(record);
                setShowDetail(true);
              }}
            >
              查看
            </a>,
            <a
              key="edit"
              onClick={() => {
                formRef.current?.resetFields();
                console.log(record);
                setCurrentRow(record);
                setEditMode(true);
                handleModalVisible(true);
              }}
            >
              编辑
            </a>,
            <Popconfirm
              key="delete"
              okButtonProps={{danger: true}}
              title={`确认删除计划：${record.name}?`}
              onConfirm={async () => {
                setCurrentRow(record);
                await handleRemove([record]);
                actionRef.current?.reloadAndRest?.();
              }}
              okText="删除"
              cancelText="取消"
            >
              <a href="#"> 删除 </a>
            </Popconfirm>,
            <a
              key="employee"
              onClick={() => {
                setCurrentRow(record);
                handleEmployeeModalVisible(true);
              }}
            >
              学员设置
            </a>,

            <a
              key="courseware"
              onClick={() => {
                setCurrentRow(record);
                handleCoursewareModalVisible(true);
              }}
            >
              课件设置
            </a>,
            <Popconfirm
              key="publish1"
              okButtonProps={{danger: true}}
              title={`确认发布计划：${record.name}?`}
              onConfirm={async () => {
                setCurrentRow(record);
                await handlePublish(record);
                actionRef.current?.reloadAndRest?.();
              }}
              okText="发布"
              cancelText="取消"
            >
              <a href="#"> 发布 </a>
            </Popconfirm>,
          ];
        } else if (record.isOwner) {
          return [
            <a
              key="view"
              onClick={() => {
                formRef.current?.resetFields();
                setCurrentRow(record);
                setShowDetail(true);
              }}
            >
              查看
            </a>,

            <a
              key="employee"
              onClick={() => {
                setCurrentRow(record);
                handleEmployeeModalVisible(true);
              }}
            >
              学员设置
            </a>,

            <Popconfirm
              key="publish"
              okButtonProps={{danger: true}}
              title={`确认取消发布计划：${record.name}?`}
              onConfirm={async () => {
                setCurrentRow(record);
                await handleUnPublish(record);
                actionRef.current?.reloadAndRest?.();
              }}
              okText="取消发布"
              cancelText="取消"
            >
              <a href="#"> 取消发布 </a>
            </Popconfirm>,
          ];
        } else
          return [
            <a
              key="view"
              onClick={() => {
                formRef.current?.resetFields();
                setCurrentRow(record);
                setShowDetail(true);
              }}
            >
              查看
            </a>,
            <a
              key="employee"
              onClick={() => {
                setCurrentRow(record);
                handleEmployeeModalVisible(true);
              }}
            >
              学员设置
            </a>,
          ];
      },
    },
    {
      title: '计划名称',
      dataIndex: 'name',
    },
    {
      title: '培训部门',
      hideInSearch: true,
      dataIndex: 'orgNameList',
      // ellipsis: true,
      render: (_, record) => (
        <>
          {record?.orgNameList?.map(function (name: string[], index: number) {
            return <Tag key={'orgNameList-' + index + record.planId}>{name.join(' - ')}</Tag>;
          })}
        </>
      ),
    },
    {
      title: '参加人数',
      hideInSearch: true,
      dataIndex: 'employeeNum',
    },
    {
      title: '是否考试',
      dataIndex: 'exam',
      align: 'center',
      valueEnum: {
        1: {
          text: '考试',
          status: 'Success',
        },
        0: {
          text: '不考试',
          status: 'Default',
        },
      },
    },
    {
      title: '是否发布',
      dataIndex: 'publish',
      align: 'center',
      valueEnum: {
        0: {
          text: '未发布',
          status: 'Error',
        },
        1: {
          text: '已发布',
          status: 'Success',
        },
      },
    },
    {
      title: '标签',
      dataIndex: 'tags',
      request: requestTag,
      valueType: 'select',
      fieldProps: {
        showSearch: true,
        mode: 'multiple',
      },
      render: (_, record) => (
        <>
          {record?.tagNames?.map((name, index) => (
            <Tag key={name + index + record.planId}>{name}</Tag>
          ))}
        </>
      ),
    },
    {
      search: false,
      title: '培训时间',
      align: 'center',
      dataIndex: 'startTime',
      render: (_, record) => {
        if (category == 1) {
          return <>{record.startTime}</>;
        } else {
          return (
            <>
              {record.startTime} 至 {record.endTime}
            </>
          );
        }
      },
    },
    {
      title: '创建时间',
      sorter: true,
      align: 'center',
      defaultSortOrder: 'descend',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      search: false,
    },
    // {
    //   title: '更新时间',
    //   sorter: true,
    //   dataIndex: 'updateTime',
    //   valueType: 'dateTime',
    //   search: false,
    // },
  ];

  const questionColumns: ProColumns<QuestionItem>[] = [
    {
      title: '序号',
      width: 50,
      align: 'center',
      dataIndex: 'index',
      valueType: 'indexBorder',
      render: (dom, entity, index) => {
        return (
          <span>
            {index +
              1 +
              ((actionQuestionRef?.current?.pageInfo?.current || 1) - 1) *
              (actionQuestionRef?.current?.pageInfo?.pageSize || 5)}
          </span>
        );
      },
    },
    {
      title: '题目',
      dataIndex: 'title',
    },
    {
      title: '选项',
      dataIndex: 'options',
      render: (_, record) => (
        <>
          {record?.options?.map((name, index) => (
            <div>
              <Tag
                icon={name.answer ? <CheckCircleOutlined/> : <></>}
                color={name.answer ? 'success' : ''}
                key={name.key + index + record.questionId}
              >
                {name.key}.{name.text}
              </Tag>
              <br/>
            </div>
          ))}
        </>
      ),
    },
  ];
  const [selectCoursewareKey, setSelectCoursewareKey] = useState<React.Key[]>([]);
  const [selectEmployeeKey, setSelectEmployeeKey] = useState<React.Key[]>([]);
  const coursewareColumns: ProColumns<CoursewareItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 50,
      align: 'center',
      render: (dom, entity, index) => {
        return (
          <span>
            {index +
              1 +
              ((actionCoursewareRef?.current?.pageInfo?.current || 1) - 1) *
              (actionCoursewareRef?.current?.pageInfo?.pageSize || 5)}
          </span>
        );
      },
    },
    {
      title: '课件名称',
      dataIndex: 'name',
    },
    {
      search: false,
      title: '时长',
      width: 100,
      dataIndex: 'time',
      render: (_, record) => (
        <>
          {Math.floor((record.time ?? 0) / 60)}分{(record.time ?? 0) % 60}秒
        </>
      ),
    },
    {
      search: false,
      title: '题数',
      width: 50,
      dataIndex: 'questionNum',
    },
  ];

  const employeeColumns: ProColumns<EmployeeListItem>[] = [
    {
      dataIndex: 'index',
      width: 48,
      align: 'center',
      valueType: 'index',
      render: (dom, entity, index) => {
        return (
          <span>
            {index +
              1 +
              ((actionEmployeeRef?.current?.pageInfo?.current || 1) - 1) *
              (actionEmployeeRef?.current?.pageInfo?.pageSize || 5)}
          </span>
        );
      },
    },
    {
      title: '员工姓名',
      key: 'name',
      dataIndex: 'name',
    },
    {
      title: '手机号',
      key: 'mobile',
      dataIndex: 'mobile',
    },
    {
      title: '身份证号',
      key: 'idCard',
      dataIndex: 'idCard',
    },
  ];
  const [editMode, setEditMode] = useState<boolean>(false);
  const [autoStatus, setAutoStatus] = useState<boolean>(true);
  const [autoLoading, setAutoLoading] = useState<boolean>(true);
  const [previewData, setPreviewData] = useState({
    visible: false,
    image: '',
    title: '',
  });

  const uploadProps = {
    headers: {
      Authorization: `Bearer ${localStorage.getItem('token')}`,
    },
    multiple: false,
    // onPreview: async (file: UploadFile) => {
    //   window.open(file?.response?.data?.path || file.url, '_blank')
    // },
    name: 'file',
    max: 1,
  };
  const handleCloseSelectCoursewareModal = () => {
    handleSelectCoursewareModalVisible(false);
  };

  const handleSaveSelectCoursewareModal = async () => {
    const hide = message.loading('正在保存课件');
    if (!currentRow) return true;
    try {
      await coursewareListSave(currentRow?.planId, selectCoursewareKey);
      hide();
      message.success('课件保存成功，即将刷新');
      handleSelectCoursewareModalVisible(false);
      // @ts-ignore
      actionCoursewareRef?.current?.reloadAndRest();
      return true;
    } catch (error) {
      hide();
      message.error('课件保存失败，请重试');
      return false;
    }
  };
  const handleCloseSelectEmployeeModal = () => {
    handleSelectEmployeeModalVisible(false);
  };
  const handleSaveSelectEmployeeModal = async () => {
    const hide = message.loading('正在保存');
    if (!currentRow) return true;
    try {
      await employeeListSave(currentRow?.planId, selectEmployeeKey);
      hide();
      message.success('保存成功，即将刷新');
      handleSelectEmployeeModalVisible(false);
      // @ts-ignore
      actionEmployeeRef?.current?.reloadAndRest();
      return true;
    } catch (error) {
      hide();
      message.error('保存失败，请重试');
      return false;
    }
  };
  const disabledDate = (current: Moment) => {
    return current && current < moment().subtract(1, 'days').endOf('day');
  };

  const selectAllOrg = () => {
    formRef.current?.setFieldsValue({orgList: orgSelectAll});
  };
  const requestOrg = async () => {
    return loadOrgSelect({status: '0'}).then(({data}) => {
      let map = data.map((item) => {
        return [item.id];
      });
      // @ts-ignore
      setOrgSelectAll(map);
      console.log(orgSelectAll, '2222');
      sensitiveTest();
      return data;
    });
  };
  const displayRender = (labels: string[], selectedOptions: any[]) =>
    labels.map((label, i) => {
      const option = selectedOptions[i];
      if (i === labels.length - 1) {
        return <span key={option?.value}>{label}</span>;
      }
      return <span key={option?.value}>{label} / </span>;
    });

  const dropdownRender = (menus: React.ReactNode) => (
    <div>
      {menus}
      <Divider key={'xxxxxx'} style={{margin: 0}}/>
      <Button key={'ddddddddd'} type="text" block icon={<PlusOutlined/>} onClick={selectAllOrg}>
        全部选择
      </Button>
    </div>
  );
  useEffect(() => {
    checkAuto().then(s => {
      setAutoStatus(s)
      setAutoLoading(false)
    });
  }, []);
  // @ts-ignore
  return (
    <CheckModule code={'TR'}>
      <PageContainer
        waterMarkProps={{content: ''}}
        onTabChange={(k) => {
          setCategory(parseInt(k));
        }}
        tabActiveKey={category.toString()}
        tabList={[
          {
            tab: '安全培训',
            key: '0',
          },
          {
            tab: '岗前培训',
            key: '1',
          },
          {
            tab: '四新培训',
            key: '2',
          },
          {
            tab: '技能培训',
            key: '3',
          },
          {
            tab: '其它培训',
            key: '99',
          },
        ]}
      >
        <ProTable<PlanListItem, PlanListPagination>
          headerTitle={'计划列表'}
          actionRef={actionRef}
          rowKey="planId"
          search={{
            labelWidth: 120,
          }}
          scroll={{x: 2000}}
          options={false}
          toolBarRender={() => [
            <Switch
              defaultChecked={autoStatus}
              loading={autoLoading}
              checkedChildren="自动下发年度培训计划"
              unCheckedChildren="手动下发年度培训计划"
              onChange={async (checked) => {
                setAutoLoading(true);
                let data = await saveAuto(checked);
                setAutoLoading(false);
              }}/>,
            <Popconfirm
              key="gen"
              title={
                <div>
                  <div>
                    将要根据认证类别生成对应的培训计划
                  </div>
                  <div>确认是否生成本月培训计划?</div>
                </div>
              }
              onConfirm={async () => {
                // setSpinning(true);
                await genPlan();
                // setSpinning(false);
                message.success('操作成功');
                actionRef.current?.reload();
              }}
              okText="生成计划"
              cancelText="取消"
            >
              <Button
                type="primary"
                key="first"
              >
                生成本月培训计划
              </Button>
            </Popconfirm>,
            <Button
              type="primary"
              key="primary"
              onClick={() => {
                setEditMode(false);
                handleModalVisible(true);
              }}
            >
              <PlusOutlined/> 新建
            </Button>,
          ]}
          request={dataList}
          columns={columns}
          // @ts-ignore
          params={{category}}
        />
        <ModalForm<PlanBody>
          title={currentRow?.planId || 0 > 0 ? '编辑计划' : '新建计划'}
          formRef={formRef}
          layout={'horizontal'}
          labelCol={{span: 4}}
          wrapperCol={{span: 18}}
          visible={createModalVisible}
          onValuesChange={(changedValues) => {
            if (changedValues && changedValues.hasOwnProperty('dateRange')) {
              formRef.current?.setFieldsValue({
                startTime: changedValues.dateRange[0] + ' 00:00:00',
              });
              formRef.current?.setFieldsValue({
                endTime: changedValues.dateRange[1] + ' 00:00:00',
              });
            }
          }}
          onVisibleChange={(visible) => {
            if (!visible) {
              setCurrentRow(undefined);
            }
            handleModalVisible(visible);
          }}
          modalProps={{destroyOnClose: true, maskClosable: false}}
          onFinish={async (value) => {
            console.log(value);
            const success = await handleAdd(value, editMode);
            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                // @ts-ignore
                actionRef.current?.reloadAndRest();
              }
            }
          }}
          request={async (param) => {
            console.log(param);
            if (param.planId > 0) {
              const {data} = await loadData(param as PlanBody);
              data.dateRange = [data.startTime ?? '', data.endTime ?? ''];
              if (data.startTime) data.startTime = data.startTime + ' 00:00:00';
              if (data.endTime) data.endTime = data.endTime + ' 00:00:00';
              if (data.tags) data.tagList = data.tags;
              return data;
            } else {
              return new Promise<PlanBody>((resolve) => {
                resolve({
                  planId: 0,
                  coursewareType: 1,
                  exam: 1,
                  orgList: category == 1 ? orgSelectAll : undefined,
                });
              });
            }
          }}
          params={{...currentRow}}
        >
          <ProFormText hidden name="planId"/>
          <ProFormText hidden name="startTime"/>
          <ProFormText hidden name="endTime"/>
          <ProFormText hidden name="sort" initialValue={0}/>
          <ProFormText hidden name="category" initialValue={category}/>
          <ProFormText rules={[{required: true}]} label={'计划名称'} name="name"/>
          <ProFormCascader
            name="orgList"
            label="培训部门"
            extra={<a onClick={selectAllOrg}>全选部门</a>}
            request={requestOrg}
            fieldProps={{
              multiple: true,
              // @ts-ignore
              displayRender: displayRender,
              dropdownRender: dropdownRender,
              fieldNames: {
                label: 'label',
                value: 'id',
                children: 'children',
              },
            }}
            rules={[{required: true}]}
          />
          <ProFormRadio.Group
            name="coursewareType"
            rules={[{required: true, message: '请选择课件类型'}]}
            label="课件类型"
            extra={'视频可以选择多个课件，PDF文档只能选择一个'}
            options={[
              {
                label: '视频',
                value: 1,
              },
              {
                label: 'PDF文档',
                value: 2,
              },
            ]}
          />
          <ProFormRadio.Group
            name="exam"
            rules={[{required: true, message: '请设置是否需要考试'}]}
            label="是否需要考试"
            options={[
              {
                label: '考试',
                value: 1,
              },
              {
                label: '不考试',
                value: 0,
              },
            ]}
          />
          <ProFormDependency name={['exam']}>
            {({exam}) => {
              if (exam == 1) {
                return (
                  <ProFormDigit
                    label="及格分数"
                    rules={[{required: true}]}
                    name="examPassScore"
                    min={0}
                    max={100}
                    fieldProps={{precision: 0}}
                  />
                );
              }
              return <></>;
            }}
          </ProFormDependency>

          {category == 1 ? (
            <ProFormDatePicker
              rules={[{required: true}]}
              name="startTime"
              label="开始时间"
              fieldProps={{disabledDate}}
            />
          ) : (
            <ProFormDateRangePicker
              rules={[{required: true}]}
              name="dateRange"
              label="培训时间"
              fieldProps={{disabledDate}}
            />
          )}

          <ProFormSelect
            name="tagList"
            label="计划标签"
            mode={'tags'}
            request={requestTag}
            // valueEnum={{
            //   open: '未解决',
            //   closed: '已解决',
            // }}
            extra={'没有合适的标签可以直接输入'}
            placeholder="请选择计划标签，没有合适的标签可以直接输入"
            rules={[{required: true, message: '请设置计划标签!'}]}
          />
        </ModalForm>
        <DrawerForm<PlanBody>
          title={'课程设置'}
          formRef={formCoursewareRef}
          layout={'horizontal'}
          labelCol={{span: 4}}
          wrapperCol={{span: 18}}
          visible={coursewareModalVisible}
          onValuesChange={(changedValues, values) => {
            console.log(changedValues);
            if (changedValues && changedValues.hasOwnProperty('coursewareType')) {
              setCoursewareType(values.coursewareType);
            }
          }}
          onVisibleChange={(visible) => {
            if (!visible) {
              setCurrentRow(undefined);
            }
            handleCoursewareModalVisible(visible);
          }}
          drawerProps={{
            destroyOnClose: true,
            maskClosable: false,
          }}
          submitter={{
            searchConfig: {
              submitText: '保存',
              resetText: '取消',
            },
          }}
          onFinish={async (value) => {
            console.log(value);
            const success = await handleSaveCourse(value);
            if (success) {
              handleCoursewareModalVisible(false);
              // @ts-ignore
              actionRef?.current?.reloadAndRest();
            }
          }}
          // @ts-ignore
          request={(params: PlanBody) => {
            console.log(params);
            if (params.planId) {
              return loadData(params).then(({data}) => {
                data.dateRange = [data.startTime ?? '', data.endTime ?? ''];
                data.startTime = data.startTime + ' 00:00:00';
                data.endTime = data.endTime + ' 00:00:00';
                if (data.tags) data.tagList = data.tags;
                setCoursewareType(data.coursewareType ?? 0);

                return data;
              });
            }
          }}
          params={{...currentRow}}
        >
          <ProFormText hidden name="planId"/>
          <ProFormText readonly label={'计划名称'} name="name"/>
          <ProFormRadio.Group
            name="coursewareType"
            label="课件类型"
            extra={'视频可以选择多个课件，PDF文档只能选择一个'}
            disabled
            options={[
              {
                label: '视频',
                value: 1,
              },
              {
                label: 'PDF文档',
                value: 2,
              },
            ]}
          />
          <ProForm.Item label={'培训课件'}>
            <ProTable<CoursewareListItem>
              size={'small'}
              cardProps={{
                bodyStyle: {padding: 0},
              }}
              scroll={{y: 200}}
              // dataSource={selectCourseware}
              request={async () => {
                let newVar = await coursewareList(currentRow?.planId ?? 0);
                console.log(newVar);
                setSelectCoursewareKey(
                  newVar.data.map((row: { coursewareId: any }) => row.coursewareId),
                );

                return {
                  data: newVar.data,
                  // success 请返回 true，
                  // 不然 table 会停止解析数据，即使有数据
                  success: true,
                  // 不传会使用 data 的长度，如果是分页一定要传
                  total: newVar.data.length,
                };
              }}
              rowKey="coursewareId"
              bordered
              options={false}
              pagination={false}
              actionRef={actionCoursewareRef}
              columns={coursewareColumns}
              search={false}
              dateFormatter="string"
            />
            <div style={{textAlign: 'right'}}>
              <Button
                type="primary"
                key="primary"
                style={{marginTop: 15}}
                icon={<SearchOutlined/>}
                onClick={() => {
                  handleSelectCoursewareModalVisible(true);
                }}
              >
                选择课件
              </Button>
            </div>
          </ProForm.Item>
          <ProFormRadio.Group
            name="exam"
            rules={[{required: true, message: '请设置是否考试'}]}
            label="是否考试"
            options={[
              {
                label: '不考试',
                value: 0,
              },
              {
                label: '考试',
                value: 1,
              },
            ]}
          />
          <ProFormDependency name={['exam']}>
            {({exam}) => {
              if (exam == 1) {
                return (
                  <>
                    <ProFormDigit
                      label="及格分数"
                      rules={[{required: true}]}
                      name="examPassScore"
                      min={0}
                      max={100}
                      fieldProps={{precision: 0}}
                    />
                    <ProFormRadio.Group
                      name="questionType"
                      rules={[{required: true, message: '请设置出题方式'}]}
                      label="出题方式"
                      options={[
                        {
                          label: '所选课件的全部题目',
                          value: 0,
                        },
                        {
                          label: '在所选课件中随机抽取',
                          value: 1,
                        },
                        {
                          label: '自定义',
                          value: 2,
                        },
                      ]}
                    />

                    <ProFormDependency name={['questionType']}>
                      {({questionType}) => {
                        if (questionType == 1) {
                          return (
                            <ProFormDigit
                              label="抽取题数"
                              rules={[{required: true}]}
                              name="questionNum"
                              min={1}
                              extra={'最少抽取一道题'}
                              fieldProps={{precision: 0}}
                            />
                          );
                        } else if (questionType == 2) {
                          return (
                            <ProForm.Item label={'上传试题'}>
                              <ProTable<QuestionItem>
                                request={async () => {
                                  let newVar = await questionList(currentRow?.planId ?? 0);
                                  console.log(newVar);
                                  return {
                                    data: newVar.data,
                                    // success 请返回 true，
                                    // 不然 table 会停止解析数据，即使有数据
                                    success: true,
                                    // 不传会使用 data 的长度，如果是分页一定要传
                                    total: newVar.data.length,
                                  };
                                }}
                                rowKey={'questionId'}
                                size={'small'}
                                cardProps={{
                                  bodyStyle: {padding: 0},
                                }}
                                scroll={{y: 200}}
                                bordered
                                pagination={false}
                                columns={questionColumns}
                                options={false}
                                search={false}
                                actionRef={actionQuestionRef}
                                dateFormatter="string"
                              />
                              <div style={{textAlign: 'right', marginTop: 5}}>
                                <div style={{color: 'red', textAlign: 'right', marginBottom: 5}}>
                                  注意:上传题目将会覆盖原有题目
                                </div>
                                <div>
                                  <Button onClick={download} key={'download'}>
                                    下载模板
                                  </Button>
                                  &nbsp;&nbsp;&nbsp;
                                  <Upload
                                    key="upload"
                                    style={{width: '100%'}}
                                    {...uploadProps}
                                    accept={'.xls,.xlsx'}
                                    action={
                                      '/v2/enterprise/train/plan/question/upload/' +
                                      currentRow?.planId
                                    }
                                    showUploadList={false}
                                    onChange={async (data) => {
                                      let file = data.file;
                                      if (file.status === 'done' && file.response.code !== 200) {
                                        file.status = 'error';
                                      } else if (
                                        file.status === 'done' &&
                                        file.response.code === 200
                                      ) {
                                        // @ts-ignore
                                        actionQuestionRef?.current?.reloadAndRest();
                                      }
                                    }}
                                  >
                                    <Button type="primary" block icon={<UploadOutlined/>}>
                                      上传题目
                                    </Button>
                                  </Upload>
                                </div>
                              </div>
                            </ProForm.Item>
                          );
                        }
                        return <></>;
                      }}
                    </ProFormDependency>
                  </>
                );
              }
              return <></>;
            }}
          </ProFormDependency>
        </DrawerForm>
        <DrawerForm<PlanBody>
          title={'学员管理'}
          formRef={formCoursewareRef}
          layout={'horizontal'}
          labelCol={{span: 4}}
          wrapperCol={{span: 18}}
          visible={employeeModalVisible}
          onVisibleChange={(visible) => {
            if (!visible) {
              setCurrentRow(undefined);
            }
            handleEmployeeModalVisible(visible);
          }}
          drawerProps={{
            destroyOnClose: true,
            maskClosable: false,
          }}
          submitter={{
            searchConfig: {
              submitText: '保存',
              resetText: '关闭',
            },
            submitButtonProps: {
              style: {
                display: 'none',
              },
            },
          }}
          onFinish={async () => {
            handleEmployeeModalVisible(false);
          }}
          // @ts-ignore
          request={(params: PlanBody) => {
            console.log(params);
            if (params.planId) {
              return loadData(params).then(({data}) => {
                data.dateRange = [data.startTime ?? '', data.endTime ?? ''];
                data.startTime = data.startTime + ' 00:00:00';
                data.endTime = data.endTime + ' 00:00:00';
                if (data.tags) data.tagList = data.tags;
                setCoursewareType(data.coursewareType ?? 0);

                return data;
              });
            }
          }}
          params={{...currentRow}}
        >
          {/*<ProFormText hidden name="planId"/>*/}
          {/*<ProFormText readonly label={'计划名称'} name="name"/>*/}
          {/*<ProForm.Item label={"学员列表"}>*/}
          {/*<ProFormCascader*/}
          {/*  name="orgList"*/}
          {/*  label="培训部门"*/}
          {/*  disabled*/}
          {/*  request={requestOrg}*/}
          {/*  fieldProps={{*/}
          {/*    multiple: true,*/}
          {/*    // @ts-ignore*/}
          {/*    displayRender: displayRender,*/}
          {/*    fieldNames: {*/}
          {/*      label: 'label', value: 'id', children: 'children',*/}
          {/*    },*/}
          {/*  }}*/}
          {/*/>*/}
          <ProForm.Item label={'学员列表'}>
            <ProTable<EmployeeListItem>
              size={'small'}
              cardProps={{
                bodyStyle: {padding: 0},
              }}
              scroll={{y: 500}}
              // dataSource={selectCourseware}
              request={async () => {
                let newVar = await employeeList(currentRow?.planId ?? 0);
                console.log(newVar);
                // @ts-ignore
                setSelectEmployeeKey(newVar.data.map((row) => row.employeeId));

                return {
                  data: newVar.data,
                  // success 请返回 true，
                  // 不然 table 会停止解析数据，即使有数据
                  success: true,
                  // 不传会使用 data 的长度，如果是分页一定要传
                  total: newVar.data.length,
                };
              }}
              rowKey="employeeId"
              bordered
              options={false}
              pagination={false}
              actionRef={actionEmployeeRef}
              columns={employeeColumns}
              search={false}
              dateFormatter="string"
            />
            <div style={{textAlign: 'right'}}>
              <Button
                type="primary"
                key="primary"
                style={{marginTop: 15}}
                icon={<SearchOutlined/>}
                onClick={() => {
                  handleSelectEmployeeModalVisible(true);
                }}
              >
                选择学员
              </Button>
            </div>
          </ProForm.Item>
        </DrawerForm>

        <Modal
          title={'课件选择'}
          visible={selectCoursewareModalVisible}
          onOk={handleSaveSelectCoursewareModal}
          onCancel={handleCloseSelectCoursewareModal}
          destroyOnClose={true}
          bodyStyle={{padding: 20, background: '#f0f2f5'}}
          width={1000}
          maskClosable={false}
        >
          <CoursewareList
            selectMode={true}
            type={coursewareType}
            keys={selectCoursewareKey}
            onSelectData={(_, __) => {
              console.log(_, __);
              setSelectCoursewareKey(_);
            }}
          />
        </Modal>
        <Modal
          title={'学员选择'}
          visible={selectEmployeeModalVisible}
          onOk={handleSaveSelectEmployeeModal}
          onCancel={handleCloseSelectEmployeeModal}
          destroyOnClose={true}
          bodyStyle={{padding: 20, background: '#f0f2f5'}}
          width={1000}
          maskClosable={false}
        >
          <PlanEmployeeSelect
            keys={selectEmployeeKey}
            planId={currentRow?.planId ?? 0}
            onSelectData={(_, __) => {
              console.log(_, __);
              setSelectEmployeeKey(_);
            }}
          />
        </Modal>
        <Image
          width={200}
          style={{display: 'none'}}
          src={previewData.image}
          preview={{
            visible: previewData.visible,
            src: previewData.image,
            onVisibleChange: (value) => {
              setPreviewData({image: previewData.image, title: '', visible: value});
            },
          }}
        />
        <Drawer
          width={800}
          visible={showDetail}
          onClose={() => {
            setCurrentRow(undefined);
            setShowDetail(false);
          }}
          closable={false}
        >
          {currentRow?.planId && (
            <ProDescriptions<PlanBody>
              column={1}
              bordered={true}
              title={'计划详情'}
              // @ts-ignore
              request={loadData}
              // layout={'vertical'}
              params={currentRow}
              columns={columns as ProDescriptionsItemProps<PlanBody>[]}
            />
          )}
        </Drawer>
      </PageContainer>
    </CheckModule>
  );
};

export default PlanPage;
